package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.BabyQRCodeResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteEditGroup;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.orhanobut.logger.Logger;

public class NoticeDiaryActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener {
    private RelativeLayout relativeLayout_lianxiren,relativeLayout_saoyisao;
    private String cNumber;
    private CuteTextView tv_phone;
    private LinearLayout linearlayout_search;
    private ImageView iv_search;
    private CuteEditGroup editText_search;
    private CuteEditText ed;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.REQUEST_OPEN_SCAN && resultCode == Activity.RESULT_OK) {
//            getBabyIDByQRCode(data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_QRCDOE));
            Intent intent = new Intent(NoticeDiaryActivity.this,JoinNewActivity.class);
            intent.putExtra("QRCodeName",data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_QRCDOE));
            startActivity(intent);
        }else if (requestCode == 1 && resultCode == Activity.RESULT_OK){
            Uri contactData = data.getData();
            Cursor c = NoticeDiaryActivity.this.managedQuery(contactData, null, null, null, null);
            if (c.moveToFirst()) {
                String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                if (hasPhone.equalsIgnoreCase("1")) {
                    Cursor phones = NoticeDiaryActivity.this.getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                            null, null);
                    phones.moveToFirst();
                    cNumber = phones.getString(phones.getColumnIndex("data1"));
                    cNumber = cNumber.replace(" ", "");
                    cNumber = cNumber.replace("-", "");
                    cNumber = cNumber.substring(cNumber.length() - 11, cNumber.length());
                    phones.close();
                }
            }
            Intent intent = new Intent(NoticeDiaryActivity.this, JoinNewActivity.class);
            intent.putExtra("searchPhone", cNumber.trim());
            startActivity(intent);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice_diary);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.notice_diary_cutetoolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        init();
    }
    private void init(){
        editText_search = (CuteEditGroup) findViewById(R.id.edit_for_search);
        editText_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ed.setFocusable(true);
                ed.setFocusableInTouchMode(true);
                ed.requestFocus();
            }
        });
        iv_search = (ImageView) findViewById(R.id.iv_search);
//        iv_search.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                    if (v.getId() == R.id.iv_search) {
//                        String searchPhone = editText_search.getText().toString();
//                        if (TextUtils.isEmpty(searchPhone) || searchPhone.length() != 11) {
//                            tipShow("请输入正确的手机号");
//                            return;
//                        }
//                        Intent intent = new Intent(NoticeDiaryActivity.this, JoinNewActivity.class);
//                        intent.putExtra("searchPhone", editText_search.getText().toString());
//                        startActivity(intent);
////                        finish();
//                    }
//            }
//        });
        ed = (CuteEditText) editText_search.findViewById(R.id.edit);
        ed.setImeOptions(EditorInfo.IME_ACTION_SEND);
        ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    //do something;
                    String searchPhone = ed.getText().toString();
                    if (TextUtils.isEmpty(searchPhone) || searchPhone.length() != 11) {
                        tipShow("请输入正确的手机号");
                        return false;
                    }
                    Intent intent = new Intent(NoticeDiaryActivity.this, JoinNewActivity.class);
                    intent.putExtra("searchPhone", ed.getText().toString());
                    startActivity(intent);
                    return true;
                }
                return false;
            }
        });
        LoginInfo loginInfo = Config.getLoginInfo(NoticeDiaryActivity.this);
        tv_phone = (CuteTextView) findViewById(R.id.diary_notice_phone);
        tv_phone.setText("我的成长日记帐号:"+loginInfo.getPhone());
//        linearlayout_search  = (LinearLayout) findViewById(R.id.linearlayout_search);
//        linearlayout_search.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                Intent intent = new Intent(NoticeDiaryActivity.this,SearchPhoneActivity.class);
////                startActivity(intent);
//            }
//        });
        relativeLayout_lianxiren = (RelativeLayout) findViewById(R.id.relativeLayout_lianxiren);
        relativeLayout_lianxiren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 1);
            }
        });
        relativeLayout_saoyisao = (RelativeLayout) findViewById(R.id.relativeLayout_saoyisao);
        relativeLayout_saoyisao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startCaptureActivityForResult();
            }
        });
    }
    private void startCaptureActivityForResult() {
        Intent intent = new Intent(NoticeDiaryActivity.this, CaptureActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_SCAN);
    }
    // 根据二维码获得宝贝信息
    private void getBabyIDByQRCode(String qrcode) {
        LoginInfo login = Config.getLoginInfo(NoticeDiaryActivity.this);
        if (login == null) {
            return;
        }
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
//        String member = mInputName.getText().toString();
        String member = "";
        Client.requestBabyQRCode(NoticeDiaryActivity.this, phone, token, member, qrcode, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Logger.d("扫码结果" + value.toString());
                BabyQRCodeResponse response = get(value.toString(), BabyQRCodeResponse.class);
                if (response != null) {
//                    requestJoin(response.getId());
                    Intent intent = new Intent(NoticeDiaryActivity.this,JoinNewActivity.class);
                    intent.putExtra("babyId",response.getId());
                    startActivity(intent);
                }
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }
        }, networkUnavailableSampleImpl());
    }

    private void requestJoin(int babyID) {
        LoginInfo loginInfo = Config.getLoginInfo(NoticeDiaryActivity.this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
//        String role = mInputName.getText().toString();
        String role = "";
        Client.requestJoin(NoticeDiaryActivity.this, phone, token, babyID, role, new ResponseHandler() {

            @Override
            public void onStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                if (value.getAsInt() == 1) {
                    tipShow("申请成功！坐待对方验证吧！");
                    startTimelineActivity();
                } else {
                    tipShow("未知的错误");
                }
            }

            @Override
            public void onChZhRJFailure(String value) {
                tipShow(value);
            }

            @Override
            public void onInnovationFinish() {
                dismissProgressDialog();
            }

            @Override
            public void onInnovationExceptionFinish() {
                dismissProgressDialog();
            }
        }, networkUnavailableSampleImpl());
    }


    private void startTimelineActivity() {
        Intent intent = new Intent(NoticeDiaryActivity.this, TimelineActivity.class);
        startActivity(intent);
        NoticeDiaryActivity.this.finish();
    }

    @Override
    public void onClickLeft() {
        onBackPressed();
    }

    @Override
    public void onClickRight() {

    }
}
